'use client'

import { FaUser } from "react-icons/fa"
import { useEffect, useRef } from "react"
import { useSearchParams } from "next/navigation"
import { AnimatePresence, motion } from "framer-motion"

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"

import { cn } from "@/lib/utils"
import { useAvatar } from "@/hooks/use-avatar"
import { useCurrentUser } from "@/hooks/use-current-user"
import { extractJsonContent } from "@/lib/chat-extractor"
import { useChatContextSelector } from "@/context/chat-context"

const ChatListArea = () => {
    const searchParams = useSearchParams()
    const greeting = searchParams.get('greeting')

    const user = useCurrentUser()
    const avatar = useAvatar(state => state.avatar)

    const scrollRef = useRef<HTMLDivElement>(null)
    const messages = useChatContextSelector(state => state.messages)

    const adjustedMessages = greeting ? [
        {
            id: 0,
            role: 'assistant',
            content: greeting || 'Hello there! Welcome to the community!',
            name: 'Assistant'
        },
        ...messages
    ] : messages

    useEffect(() => {
        if (messages) {
            scrollRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' })
        }
    }, [messages])

    return (
        <div className="w-full overflow-y-auto overflow-x-hidden h-full flex flex-col">
            <AnimatePresence>
                {adjustedMessages?.map((message, index) => (message.role === 'assistant' || message.role === 'user') && (
                    <motion.div
                        key={index}
                        layout
                        initial={{ opacity: 0, scale: 1, y: 50, x: 0 }}
                        animate={{ opacity: 1, scale: 1, y: 0, x: 0 }}
                        exit={{ opacity: 0, scale: 1, y: 1, x: 0 }}
                        transition={{
                            opacity: { duration: 0.1 },
                            layout: { type: 'spring', bounce: 0.3, duration: adjustedMessages.indexOf(message) * 0.05 + 0.2 }
                        }}
                        style={{ originX: 0.5, originY: 0.5 }}
                        className={cn(
                            'flex flex-col gap-2 p-4 whitespace-pre-wrap',
                            message.role !== 'assistant' ? 'items-end' : 'items-start'
                        )}
                    >
                        <div className="flex gap-3 items-start">
                            {message.role === 'assistant' && (
                                <Avatar className="flex justify-center items-center">
                                    <AvatarImage
                                        src={avatar.headImage}
                                        alt={message.name}
                                        width={6}
                                        height={6}
                                    />
                                </Avatar>
                            )}
                            <span className={cn(
                                "bg-accent p-3 rounded-md hover:shadow-md",
                                message.role === 'assistant' ? 'rounded-bl-none' : 'rounded-br-none'
                            )}>{(message.role === 'assistant' && avatar.useTools) ? extractJsonContent(message.content, 'Teacher_talk') : message.content}</span>
                            {message.role === 'user' && (
                                <Avatar className='h-10 w-10 p-[2px] border'>
                                    <AvatarImage src={user?.image || ''} />
                                    <AvatarFallback className='bg-muted-foreground'>
                                        <FaUser className='text-white' />
                                    </AvatarFallback>
                                </Avatar>
                            )}
                        </div>
                    </motion.div>
                ))}
            </AnimatePresence>
            <div ref={scrollRef} />
        </div>
    )
}

export default ChatListArea